package com.vben.auth.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.vben.auth.util.ServletUtil;
import com.vben.common.core.constant.CommonConstant;
import com.vben.common.core.constant.UserAgentConstant;
import com.vben.common.core.util.R;
import com.vben.common.exception.auth.LoginException;
import com.vben.common.exception.enums.ErrorCode;
import com.vben.system.api.entity.SysUser;
import com.vben.system.api.entity.SysUserLoginLog;
import com.vben.system.api.feign.RemoteUserLoginLogService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 登陆日志服务
 *
 * @author sunn
 */
@Service
@Slf4j
public class LoginLogService {

    @Resource
    private RemoteUserLoginLogService remoteUserLoginLogService;

    /**
     * 根据loginId查询登陆日志
     */
    public SysUserLoginLog getByLoginId(String loginId) {
        R<SysUserLoginLog> getResult = remoteUserLoginLogService.getByLoginId(loginId);
        if (!R.isOk(getResult)) {
            throw new LoginException(ErrorCode.INTERNAL_ERROR);
        }
        return getResult.getData();
    }

    /**
     * 新增登陆日志
     */
    public void addLoginLog(SysUser user, String loginId, String loginStatus, HttpServletRequest request) {
        Long userId = user.getUserId();
        String username = user.getUsername();
        if (ObjUtil.isNull(userId) || StrUtil.isBlankIfStr(username)) {
            log.error("用户id或用户名为空,新增登陆日志失败");
        }
        String clientIp = UserAgentConstant.DEFAULT_CLIENT_IP;
        String deviceType = UserAgentConstant.DEFAULT_DEVICE_TYPE;
        String browser = UserAgentConstant.DEFAULT_BROWSER;
        //获取客户端ip
        String uaStr = request.getHeader(UserAgentConstant.USER_AGENT);
        UserAgent ua = UserAgentUtil.parse(uaStr);
        clientIp = ServletUtil.getClientIp(request);
        deviceType = ua.getOs().toString();
        browser = ua.getBrowser().toString();

        SysUserLoginLog loginLog = new SysUserLoginLog();

        loginLog.setLogId(IdUtil.getSnowflakeNextId());
        loginLog.setUserId(userId);
        loginLog.setUsername(username);
        loginLog.setLoginTime(LocalDateTime.now());
        loginLog.setLogoutFlag(CommonConstant.COMMON_NO);
        loginLog.setClientIp(clientIp);
        loginLog.setDeviceInfo(deviceType);
        loginLog.setBrowserInfo(browser);
        loginLog.setLoginStatus(loginStatus);
        loginLog.setLoginId(loginId);

        R<Boolean> addResult = remoteUserLoginLogService.addLoginLog(loginLog);

        if (R.isOk(addResult) && addResult.getData()) {
            log.info("用户:{}发起了一次登陆活动，记录登陆日志成功", username);
        } else {
            log.info("用户:{}发起了一次登陆活动，记录登陆日志失败:{}", username, addResult.getMessage());
        }
    }

    public void updateLoginLog(SysUserLoginLog sysUserLoginLog) {
        remoteUserLoginLogService.updateLoginLog(sysUserLoginLog);
    }

}
